<?php
namespace Modules\Box\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Box\Entities\Box;
use \Modules\Order\Entities\OrderSku;

use Validator;
use ThrowException;
use DB;

class BoxController extends Controller
{

    public function statusTotal(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();
        $total = [
            'on_stock' => Box::status('on_stock')->count(),
            'off_stock' => Box::status('off_stock')->count(),
            'sell_out' => Box::status('sell_out')->count(),
            'marked' => Box::status('marked')->count(),
        ];

        return [
            'total' => $total
        ];
    }

    public function copy(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Box::getEntity([
            'uuid' => $uuid
        ]);

        // 复制一个活动
        DB::beginTransaction();

        $info = $item->getInfo([
            'title',
            'image_tag_id',
            'tags',
            'category_ids',
            'thumb',
            'money_price',
            'score_price',
            'sku_total',
            'sku_ratio_type',
            'room_total',
            'is_presell',
            'presell_date',
            'presell_mode',
            'is_free_carriage',
            'tips',
            'exclude_card_per_day',
            'show_card_per_day',
            'detail_images',
            'is_invite_enabled',
            'invite_rule',
            'room_bg_image',
            'bg_color_mode',
            'box_top_image',
            'sku_thumb',
            'big_box_bottom',
            'big_box_top',
            'small_box_image',
            'sku_3d_image',
            'theme_mode',
            'free_tips_limit',
            'is_show_box',
            'is_exclude_box',
            'is_hidden_sku_rank'
        ]);

        $info['title'] .= '(副本)';
        $info['status'] = 0;

        $newItem = Box::create($info);

        $copyInfo = [
            'sku_type',
            'product_id',
            'type',
            'assets',
            'title',
            'number',
            'money_price',
            'score_price',
            'display_money_price',
            'display_score_price',
            'thumb',
            'level',
            'status',
            'odds',
            'probability',
            'detail_images',
        ];

        // 复制普通款奖品
        $item->normal_skus->each(function ($sku, $key) use ($newItem, $copyInfo) {
            $info = $sku->getInfo($copyInfo);
            $info['stock'] = $sku->sales + $sku->stock;
            $info['uuid'] = uniqid();
            $newItem->hidden_skus()->create($info);
        });

        // 复制隐藏款式奖品
        $item->hidden_skus->each(function ($sku, $key) use ($newItem, $copyInfo) {
            $info = $sku->getInfo($copyInfo);
            $info['stock'] = $sku->sales + $sku->stock;
            $info['uuid'] = uniqid();
            $newItem->hidden_skus()->create($info);
        });

        $newItem->createRooms($item->room_total);
        $newItem->updateCategoryRelation();

        // 调整盒子数量
        $newItem->adjustRoom();
        
        $newItem->updateSalesAndStock();

        DB::commit();

        return [];
    }


    public function index(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        // $options['with'] = ['IP'];

        $options['order_by'] = ['list_weight' => 'desc'];

        $options['with'] = ['image_tag'];

        $options['with_count'] = ['normal_skus', 'hidden_skus'];

        $list = Box::getList($options);


        $list->each(function ($item) {
            // $item->return_total = OrderSku::returnSaled()->orderType('box')->where('product_uuid', $item->uuid)->sum('total');
            $item->normal_sku_sales = $item->normal_skus()->sum('sales');
            $item->normal_sku_stock = $item->normal_skus()->sum('stock');
            $item->hidden_sku_sales = $item->hidden_skus()->sum('sales');
            $item->hidden_sku_stock = $item->hidden_skus()->sum('stock');
        });

        return $list->generateListResponse();
    }

    public function show(Request $req, $uuid)
    {
        $item = Box::getEntity([
            'uuid' => $uuid
        ]);

        $info = $item->getInfo();

        return [
            'info' => $info
        ];
    }

    public function store(Request $req)
    {
        $rule = [
            'room_total' => ['required'],
            'sku_total' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $info = $req->all();

        DB::beginTransaction();

        $item = Box::create($info);

        $item->createSkus($req->sku_total);
        $item->createRooms($req->room_total);

        $item->updateCategoryRelation();

        // 调整盒子数量
        $item->adjustRoom();

        DB::commit();

        return [
            'id' => $item->id,
            'uuid' => $item->uuid
        ];
    }

    public function update(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Box::getEntity([
            'uuid' => $uuid
        ]);

        DB::beginTransaction();

        if ($req->type === 'update') {
            $info = $req->input('attributes');

            $item->update($info);

            $item->updateCategoryRelation();

            // 调整盒子数量
            $item->adjustRoom();
        }
        elseif ($req->type == 'update_hidden') {
            $item->update([
                'hidden_title' => $req->title,
                'hidden_thumb' => $req->thumb,
                'hidden_number' => $req->number
            ]);
        }
        elseif ($req->type == 'put_on_hidden') {
            $item->update([
                'is_has_hidden' => 1
            ]);
        }
        elseif ($req->type == 'put_off_hidden') {
            $item->update([
                'is_has_hidden' => 0
            ]);
        }
        elseif ($req->type === 'mark') {
            if ($item->marked_at) {
                $item->update([
                    'marked_at' => NULL
                ]);
            }
            else {
                $item->update([
                    'marked_at' => now()
                ]);
            }
        }


        DB::commit();

        return [];
    }

    public function destroy(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Box::getEntity([
            'uuid' => $uuid
        ]);

        $item->delete();

        return [];
    }
}
